const app = getApp();
Page({
	data: {
		billId: '',
		billDetail: null,   // 账单详情
		billUi: null,       // 展示用字段（已格式化）
		houseNumber: '',    // 房屋号
		loading: true,
		error: ''
	},

	onLoad(options) {
		const billId = options.billId;
		if (!billId) {
			this.setData({ loading: false, error: '未获取到账单ID' });
			return;
		}
		this.setData({ billId });
		this.getBillDetail(billId);
	},

	// 查询账单详情，拿到金额与房屋信息
	getBillDetail(billId) {
		this.setData({ loading: true, error: '' });

		const token = wx.getStorageSync('token');
		if (!token) {
			this.setData({ loading: false, error: '未检测到登录态，请先登录' });
			return;
		}

		wx.request({
			url: `${app.globalData.baseUrl}/bilManagement/bilManagement/${billId}`,
			method: 'GET',
			header: { 'Authorization': `Bearer ${token}` },
			success: (res) => {
				console.log('账单详情响应:', res.data);
				if (res.data && res.data.code === 200 && res.data.data) {
					const bill = res.data.data;
					this.setData({ billDetail: bill, billUi: this.buildBillUi(bill) });

					// 优先直接从账单内取房屋号
					const inlineNumber = this.extractHouseNumberInline(bill);
					if (inlineNumber) {
						this.setData({ houseNumber: inlineNumber, loading: false });
						return;
					}

					// 先尝试从账单列表里匹配本账单并取 houseNumber
					this.getHouseNumberFromBillList(token, () => {
						// 列表没有取到，再尝试 houseId -> houseInfo 详情
						const houseId = this.extractHouseId(bill);
						console.log('提取到 houseId:', houseId);
						if (houseId) {
							this.getHouseNumberById(houseId, token);
						} else {
							this.setData({ houseNumber: '未知房屋号', loading: false });
						}
					});
				} else {
					this.setData({ loading: false, error: res.data?.msg || '账单查询失败' });
				}
			},
			fail: () => {
				this.setData({ loading: false, error: '网络异常，账单查询失败' });
			}
		});
	},

	// 构建展示用字段
	buildBillUi(bill) {
		return {
			amountText: this.formatAmount(bill.totalAmount),
			chargeScopeText: bill.chargeScope || '—',
			paymentMethodText: (bill.paymentMethod && bill.paymentMethod.methodName) ? bill.paymentMethod.methodName : '—',
			chargePeriodText: `${this.formatDate(bill.chargeStartTime)} - ${this.formatDate(bill.chargeEndTime)}`,
			paymentTimeText: this.formatDate(bill.paymentTime)
		};
	},

	// 金额格式化
	formatAmount(val) {
		const num = Number(val || 0);
		return num.toFixed(2);
	},

	// 日期格式化
	formatDate(str) {
		if (!str) return '—';
		try {
			const d = new Date(str);
			const y = d.getFullYear();
			const m = String(d.getMonth() + 1).padStart(2, '0');
			const day = String(d.getDate()).padStart(2, '0');
			return `${y}-${m}-${day}`;
		} catch (e) {
			return '—';
		}
	},

	// 从账单列表中按 billId 匹配并取 houseNumber（用于账单详情未内嵌房屋信息时的兜底）
	getHouseNumberFromBillList(token, onNotFound) {
		// 先用 id 过滤尝试（不依赖 residentId）
		const tryById = () => {
			wx.request({
				url: `${app.globalData.baseUrl}/bilManagement/bilManagement/list`,
				method: 'GET',
				data: { id: this.data.billId },
				header: { 'Authorization': `Bearer ${token}` },
				success: (res) => {
					console.log('账单列表(按id)响应:', res.data);
					if (res.data && res.data.code === 200 && Array.isArray(res.data.rows) && res.data.rows.length > 0) {
						// 精确按 billId 匹配，避免直接取 rows[0] 导致房屋号错误
						const match = res.data.rows.find(item => String(item.id) === String(this.data.billId));
						if (match) {
							const number = match?.houseInfo?.houseNumber || match?.house?.houseNumber || match?.house_number || '';
							if (number) {
								this.setData({ houseNumber: number, loading: false });
								return;
							}
						}
					}
					// 按 id 未拿到，再按 residentId 兜底
					tryByResident();
				},
				fail: () => tryByResident()
			});
		};

		const tryByResident = () => {
			const residentId = app.globalData?.residentId || wx.getStorageSync('residentId') || wx.getStorageSync('userInfo')?.residentId;
			if (!residentId) {
				console.warn('未获取到 residentId，无法从账单列表兜底');
				onNotFound && onNotFound();
				return;
			}
			wx.request({
				url: `${app.globalData.baseUrl}/bilManagement/bilManagement/list`,
				method: 'GET',
				data: { residentId },
				header: { 'Authorization': `Bearer ${token}` },
				success: (res) => {
					console.log('账单列表(按residentId)响应:', res.data);
					if (res.data && res.data.code === 200 && Array.isArray(res.data.rows)) {
						const match = res.data.rows.find(item => String(item.id) === String(this.data.billId));
						const number = match?.houseInfo?.houseNumber || match?.house?.houseNumber || match?.house_number || '';
						if (number) {
							this.setData({ houseNumber: number, loading: false });
							return;
						}
					}
					onNotFound && onNotFound();
				},
				fail: () => onNotFound && onNotFound()
			});
		};

		tryById();
	},

	// 从账单详情中尽可能提取房屋号
	extractHouseNumberInline(bill) {
		return (
			bill?.houseInfo?.houseNumber ||
			bill?.houseInfo?.house_number ||
			bill?.house?.houseNumber ||
			bill?.house?.house_number ||
			bill?.houseNumber ||
			bill?.house_number ||
			''
		);
	},

	// 从账单详情中尽可能提取 houseId
	extractHouseId(bill) {
		return (
			bill?.houseId ||
			bill?.house_id ||
			bill?.houseInfo?.id ||
			bill?.house?.id ||
			''
		);
	},

	// 通过 houseId 查询房屋号（增加多条可能的接口与不同数据结构解析）
	getHouseNumberById(houseId, token) {
		const id = String(houseId).trim();
		const tryUrls = [
			`${app.globalData.baseUrl}/houseInfo/houseInfo/${id}`,
			`${app.globalData.baseUrl}/houseInfo/${id}`,
			`${app.globalData.baseUrl}/houseInfo/houseInfo/getInfo/${id}`,
			`${app.globalData.baseUrl}/houseInfo/getInfo/${id}`,
			`${app.globalData.baseUrl}/houseInfo/detail/${id}`
		];

		const requestNext = (idx) => {
			if (idx >= tryUrls.length) {
				this.setData({ houseNumber: '未知房屋号', loading: false });
				return;
			}
			const url = tryUrls[idx];
			console.log('查询房屋详情尝试:', url);
			wx.request({
				url,
				method: 'GET',
				header: { 'Authorization': `Bearer ${token}` },
				success: (res) => {
					console.log('房屋详情响应:', res.data);
					const data = res.data;
					let houseNumber = '';
					if (data) {
						const payload = data.data || data.row || data.record || data.result || data.info || null;
						const rows = data.rows || [];
						const item = payload || rows[0] || null;
						if (item) {
							houseNumber = item.houseNumber || item.house_number || '';
						}
					}

					if (houseNumber) {
						this.setData({ houseNumber, loading: false });
					} else {
						requestNext(idx + 1);
					}
				},
				fail: () => requestNext(idx + 1)
			});
		};

		requestNext(0);
	},

	// 立即缴费：跳转到支付页
	handlePay() {
		const amountNum = Number(this.data.billDetail?.totalAmount || 0);
		const amount = amountNum.toFixed(2);
		const billId = this.data.billId;
		wx.navigateTo({
			url: `/service/pages/recharge/recharge?amount=${amount}&billId=${billId}`
		});
	}
});